package com.china.produce.factorys.risk;

import com.china.produce.service.risk.OpsRiskService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2023/5/25
 */
@Component
public class RiskFactory implements InitializingBean, ApplicationContextAware {
    
    private  ApplicationContext applicationContext;

    private Map<String, OpsRiskService> map = new HashMap<>();
    
    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, OpsRiskService> beansOfType = applicationContext.getBeansOfType(OpsRiskService.class);
        Collection<OpsRiskService> values = beansOfType.values();
        values.forEach(item -> {
            map.put(item.getTopic(), item);
        });
    }

    public OpsRiskService getBeanByTopic(String topic) {

        return map.getOrDefault(topic, (OpsRiskService) applicationContext.getBean("opsRiskServiceImpl"));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
